﻿using nRoute.Components.Composition;
using nRoute.Utilities;
using System;
using System.Collections.Generic;

namespace nRoute.Mapping
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class ResolveResourceMetadataAttribute
        : ResolveResourceBaseAttribute
    {
        private static readonly Type METADATA_TYPE = typeof(IDictionary<string, Object>);
        private const string TARGETTYPE_MUSTBE_METADATA_TYPE = "Metadata resolves to type IDictionary<string, Object> type, targeted type is '{0}'";

        private readonly Type _resourceType;

        public ResolveResourceMetadataAttribute(Type resourceType)
            : this(resourceType, null) { }

        public ResolveResourceMetadataAttribute(Type resourceType, string key) 
            : base(key)
        {
            Guard.ArgumentNotNull(resourceType, "resourceType");
            _resourceType = resourceType;
        }

#region Properties

        public string Key
        {
            get { return base.ResourceName; }
        }

        public Type ResourceType
        {
            get { return _resourceType; }
        }

#endregion

#region Overrides

        protected override object ResolveResource(Type targetType, ITypeBuilder typeBuilder)
        {
            Guard.ArgumentValue(targetType != METADATA_TYPE, TARGETTYPE_MUSTBE_METADATA_TYPE, targetType.FullName);

            var _resourceCatalog = typeBuilder.ResourceCatalog as IResourceCatalogEx;
            if (_resourceCatalog != null)
            {
                var _resourceLocator = string.IsNullOrWhiteSpace(this.Key) ? _resourceCatalog.GetResourceLocator(_resourceType)
                    : _resourceCatalog.GetResourceLocator(_resourceType, this.Key);
                return _resourceLocator.Metadata;
            }
            else
            {
                return null;
            }
        }

#endregion
    }
}
